package com.erpanderp.wam.ac.view.reimbursement;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;


import com.erpanderp.wam.ac.model.entity.project.ProjectAssignment;
import com.erpanderp.wam.ac.model.entity.project.ProjectAssignmentDetail;
import com.erpanderp.wam.ac.model.entity.reimbursement.ProjectPerdiem;
import com.erpanderp.wam.ac.model.entity.reimbursement.ProjectPerdiemDetail;
import com.erpanderp.wam.ac.model.service.project.ProjectAssignmentDAO;
import com.erpanderp.wam.ac.model.service.reimbursement.ProjectPerdiemDAO;
import com.erpanderp.wam.ac.model.service.reimbursement.ProjectPerdiemDetailDAO;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.EmployeeAndReporting;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.WAMHostManager;

import com.erpanderp.wam.util.ValidationUtil;

@ViewScoped
@ManagedBean
public class EditProjectPerdiemBean {
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	private ProjectPerdiem projectPerdiem = new ProjectPerdiem();
	private ProjectPerdiemDetail projectPerdiemDetail = new ProjectPerdiemDetail();
	private WAMUser wamUser = new WAMUser();
	private String projectPerdiemCode;
	private String employeeCode;
	private ProjectPerdiemDAO projectPerdiemDAO = new ProjectPerdiemDAO();
	private Employee employee = new Employee();
	private EmployeeDAO employeeDAO = new EmployeeDAO();
	private ProjectPerdiemDetailDAO projectPerdiemDetailDAO = new ProjectPerdiemDetailDAO();
	private boolean FORM_VALID;
	private String revision;
	private String projectAssignmentId;
	private ProjectAssignment projectAssignment = new ProjectAssignment();
	private ProjectAssignmentDetail projectAssignmentDetail = new ProjectAssignmentDetail();
	private ProjectAssignmentDAO projectAssignmentDAO = new ProjectAssignmentDAO();
	private EmailUtil emailUtil = new EmailUtil();
	private String EMAIL_MESSAGE;
    private EmployeeAndReporting employeeAndReporting = new EmployeeAndReporting();	
    private EmployeeAndReportingDAO employeeAndReportingDAO = new EmployeeAndReportingDAO();
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    private Employee vicePresident;
	public EditProjectPerdiemBean(){
		wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
		if(wamUser != null){
			employeeAndReporting = employeeAndReportingDAO.getEmployeeReportingDetail(wamUser.getEmployee().getEmployeeId());
			 projectPerdiemCode = request.getParameter("projectPerdiemCode");
			 employeeCode = request.getParameter("employeeId");
			 vicePresident = new EmployeeDAO().getVP();
			 revision= request.getParameter("revision");
			 projectAssignmentId = request.getParameter("projectAssignmentId");
			 projectPerdiem = projectPerdiemDAO.getProjectPerdiemByPerdiemCodeAndEmployeeId(projectPerdiemCode,wamUser.getEmployee().getEmployeeId());
			 projectAssignment = projectAssignmentDAO.getProjectAssignmentByProjectAssignmentIdAndEmployeeId(projectAssignmentId,wamUser.getEmployee().getEmployeeId());
			 projectPerdiem.setEmployee(wamUser.getEmployee());
			 projectPerdiemDetail = projectPerdiemDetailDAO.getProjectPerdiemDetailsByProjectPerdiemIdAndRevision(projectPerdiem.getProjectPerdiemId(), revision);
			 projectAssignmentDetail = projectAssignmentDAO.getProjectAssignmentDetailByProjectAssignmentId(projectAssignment.getProjectAssignmentId());
			 employee = employeeDAO.getEmployeeByEmployeeCode(employeeCode);
			 
		}else{
			ValidationUtil.gotoLoginPage();
		}
	}
	
	public void editProjectPerdiem() throws ParseException{
		
		validate();
		if(FORM_VALID){
			
	       
			projectPerdiem.setRequestStatus("ACTIVE");
		    projectPerdiem.setDateModified(new Date());
		    projectPerdiem.setModifiedBy(wamUser.getEmployee().getFirstName());
            projectPerdiemDetail.setRevision(CommonLookup.generatePerdiemRivision());
			projectPerdiemDetail.setPerdeimRequestStatus(CommonLookup.PERDIEM_INPROCESS__STATUS);
			projectPerdiemDetail.setRecommendationStatus(CommonLookup.PERDIEM_INPROCESS__STATUS);
			projectPerdiemDetail.setApprovalStatus(CommonLookup.PERDIEM_INPROCESS__STATUS);
			projectPerdiemDetail.setModifiedBy(wamUser.getEmployee().getFirstName());
			projectPerdiemDetail.setDateModified(new Date());
	
			
			System.out.println("-----------PROJECT PERDIEM ID-----------"+projectPerdiem.getProjectPerdiemId());
			System.out.println("-----------PROJECT PERDIEM CODE-----------"+projectPerdiem.getProjectPerdiemCode());
			System.out.println("-----------PROJECT PERDIEM STATUS-----------"+projectPerdiem.getStatus());
			System.out.println("-----------PROJECT PERDIEM TOTAL AMOUNT IS-----------"+projectPerdiemDetail.getTotalAmount());
			
            if(projectPerdiemDetailDAO.createProjectPerdiemDetails(projectPerdiemDetail)){
             	
            	
            	
			 FacesMessage msg = new FacesMessage("Project Perdiems Request form update successful", null);  
		     FacesContext.getCurrentInstance().addMessage(null, msg);
		     
		      
		     
			}else{
				 FacesMessage msg = new FacesMessage("Project Perdiems Request form updation failled", null);  
			     FacesContext.getCurrentInstance().addMessage(null, msg);
			}
            
            Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
			String domainName = context.getInitParameter("domainName");
			String messageString ="";		

		    /*
		     * MAIL TO RECOMMENDER EMAIL
		     */
			emailUtil = new EmailUtil();
			if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
				String[] to = { employeeAndReporting.getProjectManager().getEmail() };
				emailUtil.setRecieverAddresses(to);
			} else {
				String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
				System.out.println(to);
				emailUtil.setRecieverAddresses(to);
			}
					
			String requestURL = "ac/reimbursement/approveprojectperdiems.html?projectPerdiemCode=" +projectPerdiem.getProjectPerdiemCode()+"&projectAssignmentCode="+projectAssignment.getProjectAssignmentCode()+"&employeeCode="+wamUser.getEmployee().getEmployeeCode()+"&revision="+projectPerdiemDetail.getRevision();
			String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName + "/" + requestURL;
			String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST) + "/"	+ domainName + "/" + requestURL;
			
			messageString = "Dear " +employeeAndReporting.getProjectManager().getFirstName()+" "+employeeAndReporting.getProjectManager().getLastName()+
									",<br /><br />" +
									
									"<table style='border: 1px solid #d9d9d9;'>" +
							        "<tr> <td>Employee Name</td><td> : </td><td>" + projectPerdiem.getEmployee().getFirstName()+" "+projectPerdiem.getEmployee().getLastName()+"</td></tr>" +
							        "<tr> <td>Employee Id</td><td> : </td><td>" + projectPerdiem.getEmployee().getEmployeeCode()+ " </td></tr>" +
							        "<tr> <td>Travel Request Id</td><td> : </td><td>" + projectPerdiem.getProjectPerdiemCode()+ " </td></tr>" +
							       			       
							        "</table><br/>"+							       
							        "<a style='color:#FF9933;font-weight: bold;' href=\""+
							        privateLink + "\">" + "Please click here to Recommend/Reject project perdiem form request" + "</a /><br />"+
									"(Employees who are in Hyderabad office)"+"<br /><br />"+
									"<a style='color:#FF9933;font-weight: bold;' href=\""+
									publicLink + "\">" + "Please click here to Recommend/Reject project perdiem form request" + "</a /><br />"+
									"(out side Hyderabad office)"+"<br /><br />"+
									
									"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;
			emailUtil = new EmailUtil();
			emailUtil.setMessage(messageString);
			emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
			
			emailUtil.setSubject("WAM -"+wamUser.getEmployee().getFirstName()+" "+wamUser.getEmployee().getLastName() +"( "+projectPerdiem.getProjectPerdiemCode()+" ) - Project Perdiems Request");
			
			SwingWorker worker = new SwingWorker<String, Object>() {
				@Override
				protected String doInBackground() throws Exception {
					EMAIL_MESSAGE = emailUtil.processAndSendEmail();
					return null;
				}

				@Override
				protected void done() {
						System.out.println("DONE " + EMAIL_MESSAGE);		
				}
			};
			worker.execute();
			System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
            
            
		
		}else{
			System.out.println("FORM NOT VALID");
		}
	}
	
	public void totalAmountByRoomRentOnChange(){
		System.out.println("ON CHANGE LISTNER");
			//totalAmount = projectAssignmentDetail.getDailyAllowance()+projectAssignmentDetail.getAdvanceAmount()+projectAssignmentDetail.getRoomRentAdvance()+proAssignmentDetail.getRoomRentPerMonth();
		    System.out.println("ROOM RENT AMOUNT IS----------------- "+projectPerdiemDetail.getRoomRentAmount());
		
		   
		    projectPerdiemDetail.setTotalAmount(projectPerdiemDetail.getTotalAmount()+projectPerdiemDetail.getRoomRentAmount());
		    projectPerdiemDetail.setRoomRentAmount(0);
		   
		}
	public void totalAmountByMiscOnchange(){
		System.out.println("ON CHANGE LISTNER");
			//totalAmount = projectAssignmentDetail.getDailyAllowance()+projectAssignmentDetail.getAdvanceAmount()+projectAssignmentDetail.getRoomRentAdvance()+proAssignmentDetail.getRoomRentPerMonth();
		    System.out.println("ROOM RENT AMOUNT IS----------------- "+projectPerdiemDetail.getRoomRentAmount());
		
		    projectPerdiemDetail.setTotalAmount(projectPerdiemDetail.getTotalAmount()+projectPerdiemDetail.getMiscAmount());
		    projectPerdiemDetail.setMiscAmount(0);
		
		}
	

	public void calculatePerdiems(ActionEvent a){
		Date min = projectPerdiemDetail.getPerdiemFrom();
		Date max = projectPerdiemDetail.getPerdeimTo();
		System.out.println("IN DAYS CALC");
		long noOfDays = daysBetween(max, min);
		System.out.println("NO OF DAYS "+noOfDays);
	  
		projectPerdiemDetail.setPerdeimAmount(noOfDays*projectAssignmentDetail.getDailyAllowance());
		projectPerdiemDetail.setTotalAmount(projectPerdiemDetail.getTotalAmount()+noOfDays*projectAssignmentDetail.getDailyAllowance());
		
		System.out.println("TOTAL AMOUNT "+projectPerdiemDetail.getTotalAmount());
		
	}
	
	public long daysBetween(Date max, Date min)
	{
	 System.out.println("IN DAYS CALC");
	 System.out.println("IN DAYSBETWEEN METHOD");
	 System.out.println("MAX DATE :"+max);
	 System.out.println("MIN DATE :"+min);
	
	 return ((max.getTime() - min.getTime())/86400000)+1;
	}
	
	 public void validate() throws ParseException{
		 Date perdiemPeriodFrom = projectPerdiemDetail.getPerdiemFrom() != null ? projectPerdiemDetail.getPerdiemFrom(): null;
			Date perdiemPeriodTo = projectPerdiemDetail.getPerdeimTo() != null ? projectPerdiemDetail.getPerdeimTo(): null;
			
			Date roomrentPeriodFrom = projectPerdiemDetail.getRoomRentFrom() != null ? projectPerdiemDetail.getRoomRentFrom(): null;
			Date roomrentPeriodTo = projectPerdiemDetail.getRoomRentTo() != null ? projectPerdiemDetail.getRoomRentTo(): null;
			
			Date miscPeriodFrom = projectPerdiemDetail.getMiscFrom() != null ? projectPerdiemDetail.getMiscFrom(): null;
			Date miscPeriodTo = projectPerdiemDetail.getMiscTo() != null ? projectPerdiemDetail.getMiscTo(): null;
		 
		 System.out.println("IN VALIDATE METHOD");
			FORM_VALID = true;
			if(ValidationUtil.isEmpty(String.valueOf(projectPerdiemDetail.getRoomRentAmount()), "Room Rent Amount", null, FacesContext.getCurrentInstance()) != null){
				System.out.println("---------ROOM RENT AMOUNT IS EMPTY-----------");
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty(String.valueOf(projectPerdiemDetail.getMiscAmount()), "Perdiem Amount", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty(String.valueOf(projectPerdiemDetail.getPerdeimAmount()), "Perdiems total", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty(String.valueOf(projectPerdiemDetail.getTotalAmount()), "Total Amount", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty((projectPerdiemDetail.getRoomRentFrom() != null)?projectPerdiemDetail.getRoomRentFrom().toString() : null, "Room Rent From", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty((projectPerdiemDetail.getRoomRentTo() != null)?projectPerdiemDetail.getRoomRentTo().toString() : null, "Room Rent To", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty((projectPerdiemDetail.getPerdiemFrom() != null)?projectPerdiemDetail.getPerdiemFrom().toString() : null, "Perdime From", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty((projectPerdiemDetail.getPerdeimTo() != null)?projectPerdiemDetail.getPerdeimTo().toString() : null, "Perdime To", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty((projectPerdiemDetail.getMiscFrom() != null)?projectPerdiemDetail.getMiscFrom().toString() : null, "Miscellaneous From", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(ValidationUtil.isEmpty((projectPerdiemDetail.getMiscTo() != null)?projectPerdiemDetail.getMiscTo().toString() : null, "Miscellaneous To", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID = false;
			}
			if(projectPerdiemDetail.getMiscAmount() == 0){
				FORM_VALID = false;
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Miscellaneous amount should not zero.", ""));
			}
			if(projectPerdiemDetail.getPerdeimAmount() == 0){
				FORM_VALID = false;
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Perdiem amount should not zero.", ""));
			}
			if(projectPerdiemDetail.getRoomRentAmount() == 0){
				FORM_VALID = false;
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Room rent amount should not zero.", ""));
			}
			if(projectPerdiemDetail.getTotalAmount() == 0){
				FORM_VALID = false;
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Total  amount should not zero.", ""));
			}
			if(perdiemPeriodFrom != null && perdiemPeriodTo != null){
				
				String fromDate = sdf.format(perdiemPeriodFrom);
				String toDate = sdf.format(perdiemPeriodTo);
				
				
				Date date1 = sdf.parse(fromDate);
		    	Date date2 = sdf.parse(toDate);
		    	if(date1.compareTo(date2)>0){
					FORM_VALID = false;
		    		System.out.println("FROMDATE is after TODATE");
		    		FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Perdiems From Date should not be more than To Date", ""));
		    	}
			}
			

			if(roomrentPeriodFrom != null && roomrentPeriodTo != null){
				
				String fromDate = sdf.format(roomrentPeriodFrom);
				String toDate = sdf.format(roomrentPeriodTo);
				
				
				Date date1 = sdf.parse(fromDate);
		    	Date date2 = sdf.parse(toDate);
		    	if(date1.compareTo(date2)>0){
					FORM_VALID = false;
		    		System.out.println("FROMDATE is after TODATE");
		    		FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Room rent From Date should not be more than To Date", ""));
		    	}
			}
			
         if(miscPeriodFrom != null && miscPeriodTo != null){
				
				String fromDate = sdf.format(miscPeriodFrom);
				String toDate = sdf.format(miscPeriodTo);
				
				
				Date date1 = sdf.parse(fromDate);
		    	Date date2 = sdf.parse(toDate);
		    	if(date1.compareTo(date2)>0){
					FORM_VALID = false;
		    		System.out.println("FROMDATE is after TODATE");
		    		FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Miscellaneous From Date should not be more than To Date", ""));
		    	}
			}
			
			System.out.println("FORM_VALID ======"+FORM_VALID);
					
			
	 }
	

	public ProjectPerdiem getProjectPerdiem() {
		return projectPerdiem;
	}

	public void setProjectPerdiem(ProjectPerdiem projectPerdiem) {
		this.projectPerdiem = projectPerdiem;
	}

	public ProjectPerdiemDetail getProjectPerdiemDetail() {
		return projectPerdiemDetail;
	}

	public void setProjectPerdiemDetail(ProjectPerdiemDetail projectPerdiemDetail) {
		this.projectPerdiemDetail = projectPerdiemDetail;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}


	public String getProjectPerdiemCode() {
		return projectPerdiemCode;
	}

	public void setProjectPerdiemCode(String projectPerdiemCode) {
		this.projectPerdiemCode = projectPerdiemCode;
	}

	public String getEmployeeCode() {
		return employeeCode;
	}

	public void setEmployeeCode(String employeeCode) {
		this.employeeCode = employeeCode;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public boolean isFORM_VALID() {
		return FORM_VALID;
	}

	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}

	public String getRevision() {
		return revision;
	}

	public void setRevision(String revision) {
		this.revision = revision;
	}

	public String getProjectAssignmentId() {
		return projectAssignmentId;
	}

	public void setProjectAssignmentId(String projectAssignmentId) {
		this.projectAssignmentId = projectAssignmentId;
	}

	public ProjectAssignment getProjectAssignment() {
		return projectAssignment;
	}

	public void setProjectAssignment(ProjectAssignment projectAssignment) {
		this.projectAssignment = projectAssignment;
	}

	public ProjectAssignmentDetail getProjectAssignmentDetail() {
		return projectAssignmentDetail;
	}

	public void setProjectAssignmentDetail(ProjectAssignmentDetail projectAssignmentDetail) {
		this.projectAssignmentDetail = projectAssignmentDetail;
	}
	
	public EmailUtil getEmailUtil() {
		return emailUtil;
	}

	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	public String getEMAIL_MESSAGE() {
		return EMAIL_MESSAGE;
	}

	public void setEMAIL_MESSAGE(String eMAIL_MESSAGE) {
		EMAIL_MESSAGE = eMAIL_MESSAGE;
	}

	public EmployeeAndReporting getEmployeeAndReporting() {
		return employeeAndReporting;
	}

	public void setEmployeeAndReporting(EmployeeAndReporting employeeAndReporting) {
		this.employeeAndReporting = employeeAndReporting;
	}

	public Employee getVicePresident() {
		return vicePresident;
	}

	public void setVicePresident(Employee vicePresident) {
		this.vicePresident = vicePresident;
	}


}
